package com.youkeyi.ddy.cloud.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.youkeyi.ddy.cloud.common.filter.BodyReaderHttpServletRequestWrapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 外部系统接入的拦截器，验证签名
 *
 * @Author liuxiawang
 * @Date18/22 3:40 PM
 * @Location shenzhen.china
 */
@Component
public class OpenApiSignInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(OpenApiSignInterceptor.class);


    @SuppressWarnings("unchecked")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isHasAuth = false;
        if (request instanceof BodyReaderHttpServletRequestWrapper) {
            String bodyStr = null;
            try {
                bodyStr = ((BodyReaderHttpServletRequestWrapper) request).getBodyStr();
                logger.info(String.format("收到来自%s(%d)的API请求：%s 参数：%s", request.getRemoteAddr(), request.getRemotePort(), request.getRequestURI(), bodyStr));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isNotBlank(bodyStr)) {
                JSONObject param = new JSONObject(true);
                LinkedHashMap<String, Object> json = JSON.parseObject(bodyStr, LinkedHashMap.class, Feature.OrderedField);
                param.putAll(json);
                // TODO: 校验签名是否一致
            }
        }
        if (!isHasAuth) {
            response.setStatus(401);
            OutputStream out = response.getOutputStream();
            String resultJson = getResult();
            out.write(resultJson.getBytes());
        }
        return isHasAuth;
    }

    private String getResult() {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", "401");
        resultMap.put("msg", "您无权使用此功能");
        return JSON.toJSONString(resultMap);
    }
}
